package com.gx.smart.building.ui.report

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.gx.smart.building.R
import com.gx.smart.building.databinding.ActivityFaultDetailBinding
import com.gx.smart.building.ui.common.activity.BaseAudioMVVMActivityV3
import com.gx.smart.building.ui.common.adapter.ImageAdapter
import com.gx.smart.building.ui.photo.activity.CustomActivity
import com.gx.smart.building.ui.photo.fragment.PhotoPreviewFragment
import com.gx.smart.building.ui.photo.model.ImageViewInfo
import com.gx.smart.building.ui.repair.adapter.RepairDetailHandleAdapter
import com.gx.smart.building.ui.repair.common.CommonHelper
import com.gx.smart.building.ui.report.viewmodel.FaultReportViewModel
import com.gx.smart.lib_http.BuildConfig
import com.huishi.gx.ib.grpc.lib.ib.app.workorder.v1.dto.WorkOrderFileDto
import com.previewlibrary.GPreviewBuilder

class FaultDetailActivity : BaseAudioMVVMActivityV3<FaultReportViewModel>() {
    private lateinit var viewBinding: ActivityFaultDetailBinding
    private lateinit var imageAdapter: ImageAdapter
    private lateinit var processAdapter: RepairDetailHandleAdapter
    private var id: String? = null
    private var isRunning: Boolean = false
    private val imageViewInfoList: MutableList<ImageViewInfo> = mutableListOf()
    override fun onBindViewModel(): Class<FaultReportViewModel> = FaultReportViewModel::class.java
    override fun onBindLayout(): Int = R.layout.activity_fault_detail
    override fun getToolbarTitle(): String = "工单详情"
    override fun initContentView(root: ViewGroup?) {
        viewBinding = ActivityFaultDetailBinding.inflate(layoutInflater, root, true)
    }


    override fun initContent() {
        super.initContent()
        imageAdapter = ImageAdapter(this)
        imageAdapter.setItemClickListener { _, position ->
            run {
                val bundle = Bundle()
                bundle.putSerializable("className", PhotoPreviewFragment::class.java)
                GPreviewBuilder.from(this)
                    .to(CustomActivity::class.java, bundle)
                    .setData(imageViewInfoList)
                    .setIsScale(true)
                    .setCurrentIndex(position)
                    .setSingleFling(true) //是否在黑屏区域点击返回
                    .setDrag(true) //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number) //指示器类型
                    .start()
            }
        }
        viewBinding.recyclerView.adapter = imageAdapter
        processAdapter = RepairDetailHandleAdapter(this)
        viewBinding.recyclerViewProgress.adapter = processAdapter
        viewBinding.save.setOnClickListener {
            submit()
        }
        viewBinding.cancel.setOnClickListener {
            cancel()
        }
        initAudioPlayer()
    }

    private fun submit() {
        val quality = viewBinding.qualityRating.rating.toInt()
        val speed = viewBinding.speedRating.rating.toInt()
        val comment = viewBinding.remarkContent.text.toString().trim()
        viewModel.evaluateTask(id!!, speed, quality, comment)
            .observe(this) {
                initData()
            }
    }

    private fun cancel() {
        viewModel.cancelTask(id!!).observe(this) {
            if (it) {
                initData()
            }
        }
    }

    override fun initData() {
        id = this.intent.getStringExtra("id")
        viewModel.queryWorkOrderDetail(id!!)
            .observe(this) { it ->
                status(it.status)
                viewBinding.status.text = CommonHelper.getStatus(it.status)
                viewBinding.orderCode.text = it.orderCode
                viewBinding.orderTypeName.text = it.orderTypeName
                viewBinding.orderSubTypeName.text = it.orderSubTypeName
                viewBinding.orderSourceName.text = it.orderSourceName
                viewBinding.releaseUserName.text = if (it.releaseUserPhone.isNotBlank()) {
                    "${it.releaseUserName}(${it.releaseUserPhone})"
                } else {
                    "${it.releaseUserName}"
                }
                viewBinding.createTime.text =
                    TimeUtils.millis2String(it.createTime, "yyyy-MM-dd HH:mm:ss")
                viewBinding.areaName.text = it.areaName
                viewBinding.assetName.text = it.assetName
                viewBinding.description.text = it.description
                //图片列表
                imageViewInfoList.clear()
//                it.workOrderFileDtoList
//                    .filter { item -> item.fileType == 1 }
//                    ?.forEach { workOrderFile ->
//                        val imageViewInfo =
//                            ImageViewInfo(BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl)
//                        imageViewInfoList.add(imageViewInfo)
//                    }
//                //1 图片 2 音频 3 视频 4 文档
//                imageAdapter.refresh(it.workOrderFileDtoList.filter { item -> item.fileType == 1 }
//                    ?.map { workOrderFile ->
//                        BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl
//                    })
                //2 音频
                val voiceList: List<WorkOrderFileDto> = listOf()
//                    it.workOrderFileDtoList.filter { item -> item.fileType == 2 }
                if (voiceList.isNullOrEmpty()) {
                    viewBinding.voiceLayout.visibility = View.GONE
                } else {
                    viewBinding.voiceLayout.visibility = View.VISIBLE
                    val duration = voiceList[0].showTimes
                    val url = BuildConfig.FILE_UPLOAD_URL + voiceList[0].fileUrl
                    viewBinding.voiceDuration.text = "${duration / 1000}''"
                    viewBinding.voiceLayout.setOnClickListener {
                        isRunning = !isRunning
                        if (isRunning) {
                            audioPlay(url)
                            Glide.with(this).asGif().load(R.drawable.ic_voice_play)
                                .into(viewBinding.voicePlay)
                        } else {
                            audioPlayPause()
                            Glide.with(this).load(R.mipmap.ic_voice_play)
                                .into(viewBinding.voicePlay)
                        }
                    }
                }
                //流程
                processAdapter.refresh(it.workOrderEventDto)
                //evaluate_task
                //是否已评价：1 是 2 否
                if (it.status == "task_complete") {
                    if (it.evaluateTask == 1) {
                        viewBinding.submitLayout.visibility = View.GONE
                        viewBinding.speedRating.rating = it.starNumber.toFloat()
                        viewBinding.speedRating.isEnabled = false
                        viewBinding.qualityRating.rating = it.starNumberQuality.toFloat()
                        viewBinding.qualityRating.isEnabled = false
                        if (it.workOrderEventDto.isNotEmpty()) {
                            val workOrderEventDto =
                                it.workOrderEventDto.find { item -> item.eventCode == "evaluate_task" }
                            val comment = workOrderEventDto?.opinion
                            viewBinding.remarkContent.setText(comment)
                        }
                        viewBinding.remarkContent.isEnabled = false
                    } else {
                        viewBinding.speedRating.isEnabled = true
                        viewBinding.qualityRating.isEnabled = true
                        viewBinding.remarkContent.isEnabled = true
                    }
                }
            }
    }

    private fun status(status: String) {
        when (status) {
            "task_cancel" -> {
                viewBinding.submitLayout.visibility = View.GONE
                viewBinding.remarkingLayout.visibility = View.GONE
            }
            "task_complete" -> {
                viewBinding.submitLayout.visibility = View.VISIBLE
                viewBinding.save.visibility = View.VISIBLE
                viewBinding.cancel.visibility = View.GONE
                viewBinding.remarkingLayout.visibility = View.VISIBLE
            }
            else -> {
                viewBinding.submitLayout.visibility = View.VISIBLE
                viewBinding.save.visibility = View.GONE
                viewBinding.cancel.visibility = View.VISIBLE
                viewBinding.remarkingLayout.visibility = View.GONE
            }
        }
    }

    override fun onPause() {
        super.onPause()
        isRunning = false
        Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
    }

    override fun playComplete() {
        isRunning = false
        Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
    }
}